package org.boge.sharpdoc.controller;

import com.github.pagehelper.PageInfo;
import org.boge.sharpdoc.bean.Customer;
import org.boge.sharpdoc.bean.DocCollect;
import org.boge.sharpdoc.bean.Document;
import org.boge.sharpdoc.bean.LayuiReturnData;
import org.boge.sharpdoc.service.DocCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("collect")
public class CollectController {
    @Autowired
    private DocCollectService docCollectService;
    @Autowired
    private HttpSession session;

    @PostMapping("addCollect")
    @ResponseBody
    public LayuiReturnData addCollect(Integer docid) {
        Customer customer = (Customer) session.getAttribute("current_customer");
        docCollectService.addCollect(customer.getPhone(), docid);
        return new LayuiReturnData(0);
    }

    @GetMapping("showCollect")
    public String showCollect(@RequestParam(defaultValue = "1") Integer index, @RequestParam(defaultValue = "5") Integer pageSize, Model model) {
        Customer customer = (Customer) session.getAttribute("current_customer");
        model.addAttribute("collected", docCollectService.findByUid(index, pageSize, customer.getPhone()));
        return "customer/myCollect";
    }

    @PostMapping("removeCollect")
    @ResponseBody
    public LayuiReturnData removeCollect(Integer docid) {
        Customer customer = (Customer) session.getAttribute("current_customer");
        docCollectService.deleteCollect(customer.getPhone(), docid);
        return new LayuiReturnData(0);
    }

    @GetMapping("admin/collectPage")
    public String collectPage() {
        return "admin/collect";
    }

    @PostMapping("admin/getAllCollect")
    @ResponseBody
    public LayuiReturnData getAllCollect(Integer index, Integer pageSize) {
        PageInfo<DocCollect> pageInfo = docCollectService.getAllWithPage(index, pageSize);
        List<DocCollect> cls = pageInfo.getList();
        for (DocCollect d : cls) {
            Customer customer = new Customer();
            customer.setPhone(d.getCustomer().getPhone());
            Document document = new Document();
            document.setDocid(d.getDocument().getDocid());

            d.setCustomer(customer);
            d.setDocument(document);
        }
        return new LayuiReturnData(0, true, "数据查询成功！", (int) pageInfo.getTotal(), cls);
    }
}